package org.duang.handles;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.duang.common.dto.DRLDto;
import org.duang.config.Config;
import org.duang.config.InstanceFactory;
import org.duang.db.elasticsearch.ESearch;
import org.duang.kit.LogKit;
import org.duang.kit.ThreadPoolKit;
import org.duang.kit.ToolsKit;
import org.duang.logs.Logger;
import org.duang.proxy.DuangProxy;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;

/**
 * DRL: duang request link
 * 用于设置请求链路的标识
 * @author laotang
 *
 */
public class DRLHandle implements IHandle {
	
	private static IndexRequestBuilder indexRequestBuilder;
	@Override
	public void execute(String target, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 如果不是开启了DRL
		if (!Config.isEnableDRL()) return;
		String drlRequestThreadId = (String)request.getAttribute(Config.DUANG_LINK_REQUEST_THREAD_ID);
		if(ToolsKit.isEmpty(drlRequestThreadId)) return ;
		if(ToolsKit.isEmpty(indexRequestBuilder)){
			indexRequestBuilder = ESearch.getInstance().getDB("drl", Config.getProductCode());
		}
		writeDRLData(drlRequestThreadId);
	}
	
	/**
	 * 起一个线程来写数据，不考虑数据丢失的问题
	 * @param drlRequestThreadId
	 */
	private void writeDRLData(final String drlRequestThreadId) {
		ThreadPoolKit.execute(new Thread() {
			public void run() {
				DRLDto dto = DuangProxy.drlDtoMap.get(drlRequestThreadId);
				boolean isException = false;
				Map<String,Map<String,String>> linkMap = InstanceFactory.getDrlUriMap();
				long useTime = 0l;
				if(ToolsKit.isNotEmpty(linkMap)) {
//					if(ToolsKit.isNotEmpty(linkMap.get(0))) useTime = Long.parseLong(linkMap.get(0).get("usetime"));
//					System.out.println(linkMap.get(0)+ "                   usetime: " + useTime);
					List<Map<String,String>> list = new ArrayList<Map<String,String>>(linkMap.size());
					for(Iterator<Entry<String,Map<String,String>>> it = linkMap.entrySet().iterator(); it.hasNext();){
						Entry<String,Map<String,String>> entry = it.next();
						Map<String,String> map =  entry.getValue();				
						if(ToolsKit.isNotEmpty(map)){
							list.add(map);
							if(useTime == 0l){ 
								useTime =Long.parseLong(map.get("usetime"));					
							}
							if(!isException){
								isException = Boolean.parseBoolean(map.get("isexception"));
							}
						}
					}
					dto.setUseTime(useTime);
					dto.setLinkList(list);
					dto.setException(isException);
					DuangProxy.isException = false;
					try {
						indexRequestBuilder.setSource(ToolsKit.toJsonString(dto)).execute().actionGet();
					} catch (Exception e) {
						e.printStackTrace();
					}
//					System.out.println("dto: " +dto.toString());
				}
				InstanceFactory.getDrlUriMap().clear();
			}
		});
	}
}
